package cn.jinjimi.app.custom.ui.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;

import cn.jinjimi.base.preference.PreferenceManager;
import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.DateUtils;
import cn.jinjimi.base.util.GsonUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.controller.CustomerController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.TagChangeEvent;
import cn.jinjimi.app.custom.entity.Custom;
import cn.jinjimi.app.custom.entity.CustomTagData;
import cn.jinjimi.app.custom.event.CustomChangeEvent;
import cn.jinjimi.app.custom.event.CustomInfoEvent;
import cn.jinjimi.app.custom.event.CustomTagGetEvent;
import cn.jinjimi.app.custom.manager.CustomsManager;
import cn.jinjimi.domain.data.dto.CustomTagDTO;
import cn.jinjimi.app.main.adapter.ExistTagAdapter;
import cn.jinjimi.app.main.dialog.CommAlertDialog;
import cn.jinjimi.app.main.dialog.LoadingDialog;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.main.widget.TagView;
import cn.jinjimi.app.bean.SharePrefKeys;
import cn.jinjimi.app.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 设置标签页
 */
public class CustomEditOrAddTagActivity extends ToolBarCommonActivity implements TagView.OnTagCheckListener,
        TextWatcher, AdapterView.OnItemClickListener {

    private TagView tagSelected;// 选中的tag
    private TagView tagAll;   // 常用的tag
    private EditText edTag;

    private ListView mListView;
    private ExistTagAdapter mAdapter;

    private List<CustomTagData> mAllTagList;                       // 常用的所有tag
    private List<CustomTagData> tagSelectedList = new ArrayList<>();//编辑框的标签,可以添加,可以删除

    private Custom mCustom;

    private static final int MAX_EMS = 20;
    private static final int MAX_LINES = 1;

    public static void launch(Context startActivity, Custom custom) {
        if (startActivity == null || custom == null)
            return;
        Intent intent = new Intent(startActivity, CustomEditOrAddTagActivity.class);
        intent.putExtra(BundleKey.PARAM_CUSTOM, custom);
        startActivity.startActivity(intent);
    }

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_edit_or_add_personal_tag);
        setTitle(getString(R.string.info_tag));
        setRightText(R.string.done);
        setSwipeEnabled(false);
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        tagSelected = (TagView) findViewById(R.id.tag_select);
        tagAll = (TagView) findViewById(R.id.tag_all);
        mListView = (ListView) findViewById(R.id.listview);

        mAdapter = new ExistTagAdapter(CustomEditOrAddTagActivity.this);
        mListView.setAdapter(mAdapter);
    }

    protected void initListener() {
        tagAll.setOnTagCheckListener(this);
        findViewById(R.id.layout).setOnClickListener(this);
        mListView.setOnItemClickListener(this);
    }

    protected void initData() {
        CustomTagDTO customTagDTO = GsonUtils.fromJson(PreferenceManager.getStringData(SharePrefKeys.PREF_CUSTOM_TAGS), CustomTagDTO.class);
        if (customTagDTO != null) {
            mAllTagList = customTagDTO.getData();
        } else {
            // 获取客户tag默认数据
            ToastUtil.showLoading(CustomEditOrAddTagActivity.this);
            CustomerController.getCustomTag();
        }

        mCustom = (Custom) getIntent().getSerializableExtra(BundleKey.PARAM_CUSTOM);
        tagSelectedList = mCustom.getTags(mAllTagList);

        tagSelected.setTagsInTopShow(tagSelectedList);
        createEditText();
        tagSelected.addView(edTag);

        tagAll.setTagsAll(mAllTagList);
        tagAll.flagTag(true, (CustomTagData[]) tagSelectedList.toArray(new CustomTagData[tagSelectedList.size()]));
    }

    /* 创建尾部的EditText */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void createEditText() {
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, getResources().getDimensionPixelOffset(R.dimen.dp_25));
        edTag = new EditText(CustomEditOrAddTagActivity.this);
        edTag.setMaxLines(MAX_LINES);//最多一行
        edTag.setTextColor(ContextCompat.getColor(CustomEditOrAddTagActivity.this, R.color.orange));
        edTag.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MAX_EMS)});//最多20个字
        edTag.setLayoutParams(layoutParams);
        edTag.setHint(getString(R.string.input_tag_content));
        edTag.setHintTextColor(ContextCompat.getColor(CustomEditOrAddTagActivity.this, R.color.hint_color));
        edTag.setBackground(ContextCompat.getDrawable(CustomEditOrAddTagActivity.this, R.drawable.selector_edit_name_text_bg));
        edTag.addTextChangedListener(this);
    }

    /* 监听各种事件 */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                if (tagSelected.getChildCount() <= 1)
                    return super.dispatchKeyEvent(event);

                if (StringUtils.isEmpty(edTag.getText().toString().trim())) {

                    CustomTagData data = (CustomTagData) tagSelected.getTagChildView().get(tagSelected.getTagChildView().size() - 1).getTag();
                    tagAll.flagTag(false, data);
                    tagSelected.removeTag(data);

                    return true;
                }
            } else if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                    && StringUtils.isNotEmpty(edTag.getText().toString().trim())) {
                addTag();
                return false;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    /* 添加标签 */
    private boolean addTag() {
        for (CheckBox checkView : tagSelected.getTagChildView()) {
            if (checkView.getText().equals(edTag.getText().toString().trim())) {
                ToastUtils.toastMessage(CustomEditOrAddTagActivity.this, getString(R.string.already_input_tag));
                return false;
            }
        }
        //无标签ID
        for (CheckBox checkBox : tagAll.getTagChildView()) {
            if (checkBox.getText().equals(edTag.getText().toString().trim())) {
                CustomTagData data = (CustomTagData) checkBox.getTag();
                if (data != null) {
                    tagAll.flagTag(true, data);
                    return true;
                }
            }
        }

        CustomTagData data = new CustomTagData(edTag.getText().toString().trim());
        if (!tagSelected.addTag(data))
            return false;

        AndroidUtils.hideSoftKeyBoard(getWindow());
        tagAll.flagTag(true, data);
        edTag.setText("");

        return true;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.layout:
                if (mListView.isShown()) {
                    mListView.setVisibility(View.GONE);
                } else {
                    if (StringUtils.isNotEmpty(edTag.getText().toString().trim())) {
                        addTag();
                    }
                }
                AndroidUtils.hideSoftKeyBoard(getWindow());
                break;

        }
    }

    @Override
    protected void rightAction() {
        super.rightAction();
        if (StringUtils.isEmpty(edTag.getText().toString().trim())) {
            if (tagSelected.getTagChildView().size() == 0) {
                commitNothingAlert();
            } else {
                saveTag();
            }
        } else {
            if (addTag()) {
                saveTag();
            }
        }
    }

    private void saveTag() {
        if (!hasEdit()) {
            finish();
            return;
        }

        List<CustomTagData> datas = new ArrayList<>();

        for (CheckBox checkBox : tagSelected.getTagChildView()) {
            CustomTagData data = (CustomTagData) checkBox.getTag();
            if (data != null) {
                datas.add(data);
            }
        }

        List<CustomTagData> newTagList = new ArrayList<>();
        List<String> tagIdList = new ArrayList<>();

        for (CustomTagData item : datas) {
            if (item.getId() != 0) {
                //有ID的
                String ids = String.valueOf(item.getId()).trim();
                tagIdList.add(ids);
            } else {
                //没有ID的,截出来添加
                newTagList.add(item);
            }
        }

        String[] stringIDs = tagIdList.toArray(new String[tagIdList.size()]);
        StringBuffer sb = new StringBuffer();
        if (stringIDs.length > 0) {
            for (String objStr : stringIDs) {
                sb.append(objStr + ",");
            }
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        String resuleLabels = sb.toString();

        updateCustom(resuleLabels, newTagList);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        CustomTagData dataItemClick = mAdapter.getItem(position - mListView.getHeaderViewsCount());
        for (CheckBox checkBox : tagSelected.getTagChildView()) {
            if (checkBox.getText().equals(dataItemClick.getName())) {
                ToastUtils.toastMessage(CustomEditOrAddTagActivity.this, getString(R.string.already_input_tag));
                return;
            }
        }
        tagSelected.addTag(dataItemClick);
        tagAll.flagTag(true, dataItemClick);

        edTag.setText("");
        mListView.setVisibility(View.GONE);
    }

    /* 删除标签后UI的变化,从tagView里面传出来 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTagChangeEvent(TagChangeEvent event) {
        for (CheckBox checkBox : tagAll.getTagChildView()) {
            if (checkBox.getText().equals(event.data.getName())) {
                checkBox.setChecked(false);
            }
        }

    }

    /* 点击每个下方tag的事件 */
    @Override
    public void onTagCheck(boolean isCheck, CustomTagData data) {
        for (CheckBox checkBox : tagSelected.getTagChildView()) {

            CustomTagData dataOrighin = (CustomTagData) checkBox.getTag();
            if (data.getName().equals(dataOrighin.getName())) {
                if (isCheck)
                    return;
                else {
                    tagSelected.removeTag(data);
                    return;
                }
            }
        }

        tagSelected.addTag(data);
    }

    /* 判断是否有修改 */
    public boolean hasEdit() {
        if (tagSelectedList.size() != tagSelected.getTagChildView().size())
            return true;

        for (int i = 0; i < tagSelectedList.size(); i++) {
            if (!tagSelectedList.get(i).getName().equals(tagSelected.getTagChildView().get(i).getText()))
                return true;
        }

        return false;
    }

    /* 放弃编辑弹出提示. */
    public void cancelEditAlert() {
        getAlertDialog().setTitle(getString(R.string.giveup_edit))
                .setMessage(getString(R.string.giveup_edit_msg))
                .setRightBtn(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();
                        finish();
                    }
                });
        getAlertDialog().setCanceledOnTouchOutside(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }

    /* 当未添加任务标签时,点击完成弹出提示. */
    public void commitNothingAlert() {
        getAlertDialog().setTitle(getString(R.string.You_are_not_adding_any_tags_for_the_time_being))
                .setMessage(getString(R.string.Whether_to_leave_the_current_page))
                .setRightBtn(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();
                        saveTag();
                    }
                });
        getAlertDialog().setCanceledOnTouchOutside(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }

    /* 重写物理返回键,效果和左上角的返回键一样 */
    @Override
    public void onBackPressed() {
        if (hasEdit()) {
            cancelEditAlert();
        } else
            super.onBackPressed();
    }


    private void updateCustom(String labels, List<CustomTagData> datas) {
        LoadingDialog.showForce(this, getString(R.string.custom_update_ing));

        mCustom.label = labels;
        mCustom.labels = datas;
        if (StringUtils.isNotEmpty(mCustom.birthday) && !DateUtils.isIllgaleDate(mCustom.birthday, new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)))
            mCustom.birthday = DateUtils.formatyymmdd(Long.valueOf(mCustom.birthday));

        CustomsManager.getInstance().updateCustom(mCustom, null);
    }

    /* 监听文本变化 */
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (StringUtils.isNotEmpty(edTag.getText().toString().trim())) {
            List<CustomTagData> mExistTagList = new ArrayList<>();

            for (CustomTagData data : mAllTagList) {
                if (data.getName().contains(edTag.getText().toString().trim())) {
                    mExistTagList.add(data);
                }
            }
            mListView.setVisibility(mExistTagList.size() > 0 ? View.VISIBLE : View.GONE);
            mAdapter.setItems(mExistTagList);

        } else {
            mListView.setVisibility(View.GONE);
        }

        if (count > 19) {
            ToastUtils.toastMessage(CustomEditOrAddTagActivity.this, "请不要输入超过20个字");
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    /* 监听请求标签接口返回的数据 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCustomTagGetEvent(CustomTagGetEvent event) {
        LoadingDialog.dispose();
        switch (event.state) {
            case CustomTagGetEvent.SUCC:
                if (event.data != null && event.data.getData() != null) {
                    initData();
                }
                break;
            case CustomTagGetEvent.FAIL:
                ToastUtils.toastMessage(CustomEditOrAddTagActivity.this, "获取标签失败，请稍后重试");
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onfinal(final CustomInfoEvent event) {
        switch (event.state) {
            case DataEvent.SUCC:
                if (event.data != null) {
                    EventBus.getDefault().post(new CustomChangeEvent(event.data, CustomChangeEvent.EVENT_UPDATE));
                    CustomerController.getCustomTag();
                    finish();
                } else {
                    ToastUtils.toastMessage(CustomEditOrAddTagActivity.this, event.msg != null ? ((String) event.msg) : getString(R.string.custom_update_fail));
                }

                break;
            case DataEvent.FAIL:
                LoadingDialog.dispose();
                ToastUtils.toastMessage(CustomEditOrAddTagActivity.this, event.msg != null ? ((String) event.msg) : getString(R.string.custom_update_fail));
                break;
        }
    }
}